// 初始化
const express = require('express')
const app = express()

const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 8081
app.set('port', port)

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
  extended: false
}))
app.use(bodyParser.json())

const cookieParser = require('cookie-parser')
app.use(cookieParser('callmeyochia'))


// 跨域控制
const origin = (req, res, next) => {
  res.header('Access-Control-Allow-Origin', req.headers.origin)
  res.header('Access-Control-Allow-Headers', 'Authorization, Content-Type')
  res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, OPTIONS, HEAD')
  res.header('Access-Control-Allow-Credentials', 'true')
  next()
}
app.all('*', origin)

// 登录校验
const loginRequired = async (req, res, next) => {
  if (req.signedCookies.NUXTDEMOUSER) {
    next()
  } else {
    res.status(401).send({ message: '当前未登录' })
  }
}

// 个人信息
app.get('/me', loginRequired, function(req, res) {
  res.send({
    loginName: req.signedCookies.NUXTDEMOUSER,
    nickname: '大爷',
    description: '要从问题的起源解决问题，只要不写代码，就不会有bug了。'
  })
})

// 文章列表
app.get('/article', loginRequired, function(req, res) {
  const list = [
    {
      title: '施主莫生气'
    }, {
      title: '生气伤身体'
    }, {
      title: '有好多篇啊'
    }, {
      title: '完蛋才编两条就编不下去了'
    }, {
      title: '那就不编了'
    }, {
      title: '1'
    }, {
      title: '2'
    }, {
      title: '3'
    }, {
      title: '4'
    }, {
      title: '5'
    }, {
      title: '6'
    }, {
      title: '7'
    }, {
      title: '8'
    }, {
      title: '9'
    }
  ]

  const pageNum = parseInt(req.query.pageNum) || 1
  const pageSize = parseInt(req.query.pageSize) || 5

  res.send(list.slice((pageNum - 1) * pageSize, pageNum * pageSize))
})

// 登录
app.post('/login', function (req, res) {
  if (req.body.loginName !== 'yochia' || req.body.password !== 'abalabala') {
    return res.status(400).send({ message: '用户名或密码错误' })
  }
  res.cookie(
    'NUXTDEMOUSER',
    req.body.loginName,
    {
      domain: 'localhost',
      expires: undefined,
      httpOnly: true,
      signed: true
    }
  )

  res.send({ message: '用户登录成功' })
})

app.listen(port, host)
console.log(`服务启动成功，开始监听端口${port}`)
